<script setup lang="ts">
import { h, ref, defineProps, nextTick, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { NFlex, NCard, NIcon, NBreadcrumb, NBreadcrumbItem, NDropdown, NButton, NBadge, useDialog , NInput, NGrid, NGridItem} from 'naive-ui'
import { createDiscreteApi, NPopover, NModal, NDrawer, NDrawerContent, NDescriptions, NDescriptionsItem } from "naive-ui";
import SvgIcon from '@/components/SvgIcon.vue'
import { APP_DEL , FORM_ADD, FOLDER_UPD, APP_INFO_GET} from "@/service/apis/from";
import { onMounted, onUnmounted } from 'vue';
import { sseService } from "../assets/utils/sse";
import type { SSEChatParams } from "../assets/utils/sse";
import { setUrl, setUrlParams } from "@/service/sseUrl";
import Papa from "papaparse";
import { useCounterStore } from './../stores/counter'
const { message } = createDiscreteApi(["message"])

const dialog = useDialog()
const breadcrumbItem: any = ref([])
const directory: any = ref([]);
const hasPermissionOfCreat= ref(false)
const hasPermissionOfDelete= ref(false)

const router = useRouter()

//接收props
const props: any = defineProps(['appId', 'currentApp', 'icon', 'title'])

const { appId, icon, title, currentApp } = props;

let currentDir = reactive([{
    name: props.currentApp['名称'],
    path: appId,
}])
/**
 * 头图标名称设置
 * 头标下拉菜单设置
 */
const options_main = [
  { label: '新建数据', key: '数据' },
  { label: '新建文件夹', key: '文件夹' },
  { label: '关闭', key: '关闭' },
]

const options_main_no_creation = [
  { label: '新建文件夹', key: '文件夹' },
  { label: '关闭', key: '关闭' },
]

const clickBreadCrumbItem = (item: any, index: number) => {
    console.log(item)
    // 截断currentDir  
    currentDir.splice(index + 1)
    reconnect()
}

let mainIcon = () => {
  console.log('应用标题', title);
  return h(NFlex, () => [
    h(NDropdown, { trigger: "hover", size: "huge", showArrow: true, options: hasPermissionOfCreat.value ? options_main : options_main_no_creation, onSelect: select }, () => h(NButton, { text: true, style: 'font-size: 24px' }, () => h(SvgIcon, { iconClass: icon }))),
    h(NBreadcrumb, { separator: '>' }, () => 
    // [
    //   h(NBreadcrumbItem, {}, () => h('div', { style: 'font-size :18px', onClick: breadItem0 }, title)),
    //   ...breadcrumbItem.value.map((breadItem: any, k: number) => h(NBreadcrumbItem, () => h('div', { style: 'font-size :18px', key: k, onClick: breadItem(breadItem, k) }, breadItem['文件名']))),
    // ]
    currentDir.map((item, index) => h(NBreadcrumbItem, { onClick: () => clickBreadCrumbItem(item, index) }, () => h('div', { style: 'font-size :18px' }, item.name)))
  ),
  ])
}

const header_main = () => mainIcon()


/**
 * 关闭事件,返回路由上一页
 */
const handleClose = () => {
  console.log('关闭不了这个应用')
  router.go(-1)
}
/**
 * 根据currentDir 计算出SSE的url
 */
 const initUrl = () => {
    let url = currentDir[0].path
    if (currentDir.length > 1) {
        url += '/'
        for (let i = 1; i < currentDir.length; i++) {
            url += `${currentDir[i].path}-`
        }
        url = url.slice(0, -1)
    }

    return url
}

const shareFrom = ref()
const shareGroup = ref([])
const getAppDataSource = () => {
  const data = {
    "app_name": props.currentApp['名称'],
  }
  APP_INFO_GET({ "params": JSON.stringify(data) }).then((res) => {
    console.log('应用信息', res.data)
    if (res.data['数据源']) {
      console.log('有数据源')
    } else {
      console.log('没数据源')
      hasPermissionOfCreat.value = true
      hasPermissionOfDelete.value = true
    }

    if (res.data['应用来源']) {
      shareFrom.value = res.data['应用来源']
    }

    if (res.data['应用共享成员'] && res.data['应用共享成员'].length > 0) {
      shareGroup.value = res.data['应用共享成员']
    }
  })
}

/**
 * 获取窗口宽度大小，以判定grid布局的显示的solt数量
 */
const windowWidth = ref<number>(window.innerWidth)
const updateWindowWidth = () => {
  windowWidth.value = window.innerWidth
}

onMounted(() => {
  sseServiceOpen(0, initUrl())
  getAppDataSource()
  window.addEventListener('resize', () => {updateWindowWidth()})
})
onUnmounted(() => {
  sseService.disconnect()
  window.removeEventListener('resize', () => {updateWindowWidth()})
})

//see 链接
function sseServiceOpen(num: number, url: string) {
  let yysx: any = appId
  const onopen = () => {
    console.log("文件夹、文件列表sse连接成功", url)
  }
  console.log('尝试创建SSE', url)
  // 建立连接
  let sseChatParams: SSEChatParams = {
    onopen,
    url: num == 1 ? setUrlParams(yysx, url) : setUrl(url),
    onmessage: (event: MessageEvent) => {
      // 收到消息
      console.log('收到消息', event.data);
      let fst = event.data.replace(/\\n/g, "\n")
      const ddf = Papa.parse(fst, { header: true, delimiter: ";", newline: "\n" })
      console.log(ddf);
      // directory.value = ddf.data
      directory.value = [...directory.value, ...ddf.data]
      console.log('文件、文件夹列表', ddf.data, directory)

    },
    finallyHandler: () => {
      console.log("finallyHandler操作")
    }
  };
  sseService.connect(sseChatParams)
}

function reconnect() {
    directory.value = []
    sseService.disconnect()
    sseServiceOpen(0, initUrl())
    getAppDataSource()
}

function breadItem0() {
  let url = appId
  sseServiceOpen(0, url)
  breadcrumbItem.value = []
}

function breadItem(val: any, num: any) {
  // console.log(val, num);
  let url = appId
  for (let index = 0; index < breadcrumbItem.value.length; index++) {
    const element = breadcrumbItem.value[index];

    if (index <= num) {
      console.log(element);
      if (index == 0) {
        url += '/' + element['缩写']
      }
      if (index > 0) {
        url += '-' + element['缩写']
      }
    }
  }
  sseServiceOpen(0, url)
  breadcrumbItem.value.splice(num + 1, breadcrumbItem.value.length)

}

function itemclick(val: any) {
  console.log('文件信息', val);
  if (val['文件格式'] == 'word' || val['文件格式'] == 'excel') {
    breadcrumbItem.value.push(val)
    directory.value = []
    sseServiceOpen(1, val['缩写'])
  } else if (val['文件格式'] == 'docx' || val['文件格式'] == 'echarts-word') {
    const info = {
      appId,
      appName: currentApp['名称'],
      type: 'word',
      fileId: val['缩写'],
      fileName: val['文件名'],
      pathUrl: initUrl()
    }
    useCounterStore().setOpenFileInfo(info)
    router.push('word');
  } else if (val['文件格式'] == 'xlsx' || val['文件格式'] == 'echarts-excel' || val['文件格式'] == 'echarts-3d') {
    const info = {
      appId,
      appName: currentApp['名称'],
      type: 'excel',
      fileId: val['缩写'],
      fileName: val['文件名'],
      pathUrl: initUrl()
    }
    useCounterStore().setOpenFileInfo(info)
    router.push('excel');
  } else if (val['类型'] == 'dir') {
    console.log(currentDir.map((item) => h('div', { style: 'font-size :18px' }, item.name)))
    currentDir.push({
        name: val.文件名,
        path: val.缩写
    })
    reconnect()
  }
}

function select(val: string) {
  if (val == '数据') {
    const appType: string = currentApp['类型'];
    const path = {
      'word': '/word',
      'excel': '/excel',
    }[appType]
    const info = {
      appId,
      appName: currentApp['名称'],
      type: appType,
      fileId: undefined,
      fileName: undefined,
      pathUrl: initUrl()
    }
    useCounterStore().setOpenFileInfo(info)
    router.push({ path });
  }

  if (val === '文件夹') {
    newFolder()
  }

  if (val == '关闭') {
    handleClose()
  }
}


let newFolderNameInputValue = ref('新建文件夹')

const newFolder = () => {
    directory.value = [...directory.value, {
        "类型": "dir",
        "need_create": true
    }]
    newFolderNameInputValue.value = '新建文件夹'
}

const saveFolderByInputValue = () => {
  const path = currentDir.length > 1 ? currentDir.slice(1).map(item => item.name).join('/') + '/' + newFolderNameInputValue.value : newFolderNameInputValue.value
    const data = {
        类型: "文件夹",
        内容: {
            应用名称: props.currentApp['名称'],
            文件夹路径: path
        }
    }
    console.log('提交的数据', data, currentDir)

    FORM_ADD({ "params": JSON.stringify(data) }).then((res: any) => {
        if (res.stacode == 200) {
            message.success(res.message)
            reconnect()
        }
    }).catch((err: any) => {
        console.log('err', err);
    })
}


let isOnDrag = false
let dragFile: any
let dropFolder: any
const onDragStart = (file: any) => {
    console.log('拖拽了：', file)
    dragFile = file
    isOnDrag = true
    showCloseButton.value = false
};

const onDragEnd = (file: any) => {
    console.log('拖拽松开了：', file)
    isOnDrag = false
    showCloseButton.value = false
};

const onDrop = (event: any, folder: any) => {
    console.log('放到了', folder)
    dropFolder = folder
    isOnDrag = false

    const currentPath = currentDir.length > 1 ? currentDir.slice(1).map(item => item.name).join('/') : ''
    const data = {
        "类型": "数据移动",
        "内容": {
            "应用名称": props.currentApp['名称'],
            "文件名": dragFile.文件名,
            "当前路径": currentPath,
            "目标路径": currentPath + '/' + folder.文件名,
        }
    }
    FOLDER_UPD({ "params": JSON.stringify(data) }).then((res: any) => {
        if (res.stacode == 200) {
            message.success(res.message)
            reconnect()
        }
    }).catch((err: any) => {
        console.log('err', err);
    })
};

let isLongPressing = false;
let longPressTimer: any
let showCloseButton = ref(false)
/**
 * 监听鼠标点击和抬起实现长按功能
 */
const handleMouseDown = () => {
  console.log('鼠标按下')
  // 阻止默认行为，比如选择文本  
  isLongPressing = false;
  // 设置长按定时器  
  longPressTimer = setTimeout(() => {
    if (isOnDrag) {
      return
    }
    isLongPressing = true;
    handleLongPress();
  }, 1200);
  setTimeout(() => {
        if (isOnDrag) {
            clearTimeout(longPressTimer);
        }
    }, 500);
}
const handleMouseUp = () => {
  console.log('鼠标抬起')
  // 清除长按定时器  
  clearTimeout(longPressTimer);
  // 重置长按状态  
  isLongPressing = false;
  // 如果需要，可以在这里处理普通的点击事件（但要确保与双击逻辑不冲突）  
  // 注意：在这个示例中，我们不处理普通的点击事件，因为它可能与双击冲突。  
  // 如果你需要处理点击事件，请确保在 handleClick 方法中进行适当的检查。  
}
const handleLongPress = () => {
  // 在这里处理长按逻辑 
  console.log('这是一次长按')
  if(hasPermissionOfDelete.value){
    showCloseButton.value = !showCloseButton.value
  }
}

const delFile = (item: any) => {
  const delItemIndex = directory.value.findIndex((element: any) => element.id === item.id);
  console.log('删除', currentApp, item, directory.value, delItemIndex)
  const currentIdPath = currentDir.length > 1 ? currentDir.slice(1).map(item =>  item.path + '/') : ''

  dialog.warning({
    title: '删除',
    content: `确定删除 ${item.文件名} ?`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      let data = {
        "应用名称": currentApp['缩写'], // 必填
        "应用类型": "数据", // 必填
        "文件类型": currentApp['类型'],
        "文件名": currentIdPath + item['缩写'],
      }

      APP_DEL({ "params": JSON.stringify(data) }).then((res: any) => {
        if (res.stacode == 200) {
          message.success(res.message)
          const delItemIndex = directory.value.findIndex((element: any) => element.id === item.id);
          if (delItemIndex !== -1) {
            directory.value.splice(delItemIndex, 1);
          }
        }
        else {
          message.error(res.message)
        }
      }).catch((err: any) => {
        console.log('err', err);
      })
    }
  })
}

/**
 * 右键菜单
 */
const showDropdown = ref(false)
const x = ref(0)
const y = ref(0)
const options: any = ref([])
const currentRightClickItem: any = ref(null)
const handleContextMenu = (e: MouseEvent, item?:any) => {
    console.log('右键菜单', e, item)
    e.preventDefault()// 阻止默认上下文菜单  
    e.stopPropagation(); // 阻止事件冒泡到父层 

    options.value = [
        { label: '新建文件夹', key: '文件夹' },
        { label: '刷新', key: '刷新' },
        { label: '关闭应用', key: '关闭' },
    ]

    if (hasPermissionOfCreat) {
      options.value = [
        { label: '新建数据文件', key: '数据' },
        ...options.value
      ]
    }
    if (hasPermissionOfDelete) {
      options.value = [
        ...options.value,
        { label: '删除数据文件', key: '删除' },
      ]
    }

    if (item) {
        options.value = [
            { label: '共享', key: '共享' },
            { type: 'divider', key: 'd1' },
            ...options.value,
            { type: 'divider', key: 'd1' },
            { label: '属性', key: '属性' }
        ]
        currentRightClickItem.value = item
    }

    showDropdown.value = false
    nextTick().then(() => {
        showDropdown.value = true
        x.value = e.clientX
        y.value = e.clientY
    })
}
const handleSelect = (key: string | number) => {
  showDropdown.value = false
  switch (key) {
    case '数据':
    case '文件夹':
    select(key)
      break;
    case '删除':
      handleLongPress()
      break;
    case '刷新':
      reconnect()
      break;
    case '关闭':
      handleClose()
      break;
    case '属性':
      handleShowPropertyDrawer()
      break;
  }
}
const showPropertyDrawer = ref(false)
const handleShowPropertyDrawer = () => {
  showPropertyDrawer.value = true
}
const showAppPropertyDrawer = ref(false)
const handleShowAppProperty = () => {
  showAppPropertyDrawer.value = true
}
const onClickoutside = () => {

  showDropdown.value = false
}
/**
 * end
 */
const  minimize = () => {
  console.log('最小化', currentApp)
  useCounterStore().updateDynamicApp(currentApp.缩写, true)
  router.go(-1)
}

const shareTo = ref('')
const showModal = ref(false)
const onShare = () => {
    console.log('共享给',shareTo.value)
    const data = {
        类型: "应用协同",
        内容: {
            应用名称: currentApp['名称'],
            编号: shareTo.value
        }
    }

    FORM_ADD({"params": JSON.stringify(data) }).then((res: any) => {
        if (res.stacode == 200) {
            message.success(res.message)
        }
        else {
            message.error(res.message)
        }
    }).catch((err: any) => {
        console.log('err', err);
        message.error(err) 
    })
}
</script>
<template>
  <n-modal v-model:show="showModal" preset="dialog" title="共享给" positive-text="确定" :on-positive-click="onShare"
    style="width: 400px">
    <n-input v-model:value="shareTo" style="margin-top: 10px;" placeholder="请输入手机号/工号" />
  </n-modal>
  <n-card :title="header_main" style="height: 100%;" content-class="scrollableContent" closable @close="handleClose"
    @contextmenu="handleContextMenu">
    <template #header-extra>
      <n-flex id="drawer-set" style="margin-right: 10px;">
        <n-button v-if="!shareFrom" text ghost size="small" type="primary" @click="showModal = true">应用协同共享</n-button>
        <n-button text ghost @click="handleShowAppProperty">属性</n-button>
      </n-flex>
      <n-button @click="minimize" size="tiny" :bordered="false" color="#ddd" quaternary>
        <n-icon>
          <SvgIcon iconClass="suoxiao3"></SvgIcon>
        </n-icon>
      </n-button>
    </template>
    <template #default>

      <div style="height: 100%;position: relative;">
        <div v-if="directory.length > 0">
          <div class="lay">
            <NGrid :x-gap="3" :y-gap="3"
              :cols="windowWidth > 1920 ? 24 : windowWidth > 1280 ? 16 : windowWidth > 1024 ? 12 : 8">
              <NGridItem v-for=" (item, index) in directory" style=" text-align: center; padding: 10px"
                @dblclick="itemclick(item)" @mousedown="handleMouseDown()" @mouseup="handleMouseUp()"
                @mouseleave="handleMouseUp()">
                <div v-if="item['类型'] === 'dir'" @dragover.prevent @drop="onDrop($event, item)">
                  <SvgIcon className="uu" iconClass="wenjiangui"></SvgIcon>
                  <NInput v-if="item.need_create" v-model:value="newFolderNameInputValue" size="small"
                    :on-blur="saveFolderByInputValue" maxlength="10" style="width: 250px;"></NInput>
                  <n-popover v-else-if="item['文件名'].length > 6" placement="bottom" trigger="hover">
                    <template #trigger>
                      <div style="white-space: nowrap; overflow: hidden;  text-overflow: ellipsis;"> {{ item['文件名'] }}
                      </div>
                    </template>
                    <span>{{ item['文件名'] }}</span>
                  </n-popover>
                  <div v-else> {{ item['文件名'] }}</div>
                </div>
                <div v-else draggable="true" @dragstart="onDragStart(item)" @dragend="onDragEnd(item)" style="cursor: pointer">
                  <n-badge value="x" color="lightGray" :show="showCloseButton"
                    @click="showCloseButton ? delFile(item) : undefined"
                    @contextmenu.prevent="handleContextMenu($event, item)">
                    <span @click.stop="console.log('点击图标，拦截事件穿透')">
                      <SvgIcon className="uu" v-if="item['文件格式'] === 'docx'" iconClass="word2"></SvgIcon>
                      <SvgIcon className="uu" v-if="item['文件格式'] === 'xlsx'" iconClass="excel4"></SvgIcon>
                      <SvgIcon className="uu" v-if="item['文件格式'] === 'echarts-excel'" iconClass="excel2"></SvgIcon>
                      <SvgIcon className="uu" v-if="item['文件格式'] === 'echarts-word'" iconClass="word3"></SvgIcon>
                      <SvgIcon className="uu" v-if="item['文件格式'] === 'echarts-3d'" iconClass="excel2"></SvgIcon>
                      <SvgIcon className="uu" v-if="item['文件格式'] === 'echarts-excel-3d'" iconClass="excel2"></SvgIcon>
                    </span>
                  </n-badge>
                  <n-popover v-if="item['文件名'].length > 6" placement="bottom" trigger="hover">
                    <template #trigger>
                      <div style="white-space: nowrap; overflow: hidden;  text-overflow: ellipsis;"> {{ item['文件名'] }}
                      </div>
                    </template>
                    <span>{{ item['文件名'] }}</span>
                  </n-popover>
                  <div v-else> {{ item['文件名'] }}</div>
                </div>
              </NGridItem>
            </NGrid>
          </div>
        </div>
        <div v-else class="svg" style="">
          <svg class="icon" aria-hidden="true">
            <use xlink:href="#wyy-guanbi7"></use>
          </svg>
          <h1 style="width:200px;">什么文件也没有</h1>
        </div>
      </div>
      <n-drawer v-model:show="showPropertyDrawer" :width="300" show-mask="transparent" placement="right" :block-scroll="false" to="#drawer-set">
        <n-drawer-content title="属性" closable>
          <n-descriptions label-placement="top" :column="1"
            :title="currentRightClickItem['文件名'] + '.' + currentRightClickItem['文件格式']">
            <n-descriptions-item label="创建时间">
              {{ currentRightClickItem['创建时间'] }}
            </n-descriptions-item>
            <n-descriptions-item label="类型">
              {{ currentRightClickItem['类型'] }}
            </n-descriptions-item>
          </n-descriptions>
        </n-drawer-content>
      </n-drawer>
      <n-drawer v-model:show="showAppPropertyDrawer" :width="300" show-mask="transparent" placement="right" :block-scroll="false" to="#drawer-set">
        <n-drawer-content title="属性" closable>
          <n-descriptions label-placement="top" :column="1"
            :title="currentApp['名称']">
            <n-descriptions-item v-if="shareFrom" label="共享来源">
              · {{ shareFrom['部门'] + ' ' +shareFrom['姓名'] }}
            </n-descriptions-item>
            <n-descriptions-item v-else label="共享状态">
              未共享
            </n-descriptions-item>
            <n-descriptions-item v-if="shareGroup && shareGroup.length > 0" label="应用范围">
              <div v-for="shareUser in shareGroup"> · {{ shareUser['部门'] + ' ' +shareUser['姓名'] }}</div>
            </n-descriptions-item>
            <n-descriptions-item v-if="!hasPermissionOfCreat" label="允许创建文件">
              否
            </n-descriptions-item>
            <n-descriptions-item v-if="!hasPermissionOfDelete" label="允许删除文件">
              否
            </n-descriptions-item>
          </n-descriptions>
        </n-drawer-content>
      </n-drawer>
      <n-dropdown placement="bottom-start" trigger="manual" :x="x" :y="y" :options :show="showDropdown"
        :on-clickoutside="onClickoutside" @select="handleSelect" />
    </template>


  </n-card>

</template>
<style scoped>
.components-main {

  background-color: #2169d6;
}

.lay {
  display: flex;
  flex-wrap: wrap;

  overflow-x: hidden;
}

.icon {
  width: 5em;
  height: 5em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
  text-align: center;
}

.svg {
  position: absolute;
  width: 200px;
  height: 50px;
  top: 50%;
  left: 50%;
  margin-left: -50px;
  margin-top: -100px;
  text-align: center;
}

.uu {
  width: 4em;
  height: 4em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>